package com.plentitude.easytrader.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;


/**
 * Has methods to get/post product keys, authenticate user and so on.
 * 
 * @author team@getstarted.com.ua
 */
public class SecurityManager {
	private final static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
	private Random random;
	
	
	private Random getRandom() {
    	if(random == null) {
    		random = new Random();
    	}
    	return random;
    }
	
	/** Send requests to generate new product key */
	public String changeProductKey(String username) {
		String ret = null;
		String randomKey = generateRandomKey();
		String changeKeyUrl = String.format(Keys.CHANGE_KEY_URL, username, randomKey);
		String getKeyUrl = String.format(Keys.GET_KEY_URL, username);
		InputStream is = null; 
		DefaultHttpClient httpclient = null;
		HttpGet httpget = null;
		// Change product key
		try {
			httpget = new HttpGet(changeKeyUrl);
	        httpclient = new DefaultHttpClient(ETApplication.getInstance().getConnectionManager(), ETApplication.getInstance().getHttpParams());
	        HttpResponse response = httpclient.execute(httpget);
	        if(200 == response.getStatusLine().getStatusCode()) {
				// Get new product key
	        	httpget = new HttpGet(getKeyUrl);
		        response = httpclient.execute(httpget);
		        HttpEntity entity = response.getEntity();
		        if(entity != null) {
			        is = entity.getContent();
			        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Keys.UTF8), 19);
			        ret = reader.readLine();
			        entity.consumeContent();
		        }
	        }
		} catch(Exception e) {
			if(httpget != null) {
				httpget.abort();
			}
        	Log.e(this.getClass().getName(), e.toString());
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
		        	Log.e(this.getClass().getName(), e.toString());
				}
			}
			/*if(httpclient != null) {
				try {
					httpclient.getConnectionManager().shutdown(); // Close the instance here
				}catch(IllegalStateException e) {
					Log.e(this.getClass().getName(), e.toString());
				}
			}*/
		}
		return ret;
	}

	/** Send request to get product key */
	public String getProductKey(String username) {
		String ret = null;
		String getKeyUrl = String.format(Keys.GET_KEY_URL, username);
		InputStream is = null; 
		DefaultHttpClient httpclient = null;
		HttpGet httpget = null;
		// Change product key
		try {
	        httpget = new HttpGet(getKeyUrl);
	        httpclient = new DefaultHttpClient(ETApplication.getInstance().getConnectionManager(), ETApplication.getInstance().getHttpParams());
	        HttpResponse response = httpclient.execute(httpget);
		    HttpEntity entity = response.getEntity();
		    if(entity != null) {
			    is = entity.getContent();
			    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Keys.UTF8), 19);
			    ret = reader.readLine();
		        entity.consumeContent();
		    }
		} catch(Exception e) {
			if(httpget != null) {
				httpget.abort();
			}
        	Log.e(this.getClass().getName(), e.toString());
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
		        	Log.e(this.getClass().getName(), e.toString());
				}
			}
			/*if(httpclient != null) {
				try {
					httpclient.getConnectionManager().shutdown(); // Close the instance here
				}catch(IllegalStateException e) {
					Log.e(this.getClass().getName(), e.toString());
				}
			}*/
		}
		return ret;
	}

	
	// PRIVATE METHODS
	
	/** Generates random letters key in format: RAND-OMST-RING-OFLE */
	private String generateRandomKey() {
		StringBuilder key = new StringBuilder(19);
		int len = alphabet.length();
		for(int i=0; i<16; i++) {
			switch(i) {
				case 4:
				case 8:
				case 12: key.append('-');  
			}
			int position = Math.abs(getRandom().nextInt()) % len; 
			key.append(alphabet.charAt(position));
		}
		return key.toString();		
	}	
	
}
